package net.hmr_radio.hmrbot.controller.login;

import java.util.List;

import net.hmr_radio.hmrbot.model.Bot;
import net.hmr_radio.hmrbot.model.UserInfo;
import net.hmr_radio.hmrbot.service.BotService;
import net.hmr_radio.hmrbot.service.UserInfoService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import twitter4j.Twitter;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class ByGoogleSuccessController extends Controller {

    private UserService userService = UserServiceFactory.getUserService();
    private UserInfoService userInfoService = new UserInfoService();

    private BotService botService = new BotService();

    @Override
    public Navigation run() throws Exception {

        User googleAccount = null;
        if (userService.isUserLoggedIn()) {
            googleAccount = userService.getCurrentUser();
        } else {
            return forward("/login/error");
        }

        UserInfo user = userInfoService.get(googleAccount);
        if (user == null) {
            user = userInfoService.createNewUser(googleAccount);
        }

        request.getSession().invalidate();
        sessionScope("loginUser", user);

        // ボットが一体でもいればそいつを使ってTwitterへログイン
        List<Bot> bots = botService.findByUserId(user.getUserId());
        if (!bots.isEmpty()) {
            Twitter twitter = bots.get(0).createTwitterOrNull();
            sessionScope("twitter", twitter);
        }

        return redirect("/mypage/");
    }
}
